package com.neusoft.service.impl;

import com.neusoft.mapper.CouponMapper;
import com.neusoft.mapper.PointMapper;
import com.neusoft.po.Coupon;
import com.neusoft.service.CouponService;
import com.neusoft.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private PointMapper pointMapper;


    @Override
    @Transactional
    public Coupon getCouponById(String userId) {
        //检查优惠券是否过期
        Coupon coupon = couponMapper.getCouponById(userId);
        String curDate = CommonUtil.getCurrentDate();
        int result0 =CommonUtil.checkDate(curDate, coupon.getStartDate(),30);
        if(result0==0) {
            couponMapper.cleanCoupon(coupon);
            coupon = couponMapper.getCouponById(coupon.getUserId());
            coupon.setExpireRemain(30);
        }else {
            coupon.setExpireRemain(result0);
        }
        return coupon;
    }


    @Override
    @Transactional
    public Coupon addCoupon(Coupon coupon) {
        String curDate = CommonUtil.getCurrentDate();
        Coupon coupon2 = couponMapper.getCouponById(coupon.getUserId());
        int result =CommonUtil.checkDate(curDate, coupon2.getStartDate(),30);
        if(result==0) {
            coupon.setStartDate(curDate);
            couponMapper.cleanCoupon(coupon);
        }
        coupon.setStartDate(CommonUtil.getCurrentDate());
        couponMapper.addCoupon(coupon);
        coupon = couponMapper.getCouponById(coupon.getUserId());
        coupon.setExpireRemain(30);
        return coupon;
    }
}
